
import { ERR_INVALID_STATE, ERR_SWITCH_STATE } from "../../../extention/return_code";
import { jobGoto } from "../../../job/goto";
import { GroupTerminal } from "../terminal_group";

export class GroupWork extends GroupTerminal{
    // constructor(spawnRoom=undefined, minResourceLevel=undefined, maxResourceLevel=undefined){
    //     super(spawnRoom);
    //     this.minResourceLevel = minResourceLevel;
    //     this.maxResourceLevel = maxResourceLevel;
    // }

    serialize(){
        return {super: super.serialize()};
    }
    deserialize(obj){
        super.deserialize(obj.super);
        return this;
    }

    run(...args){
        for(let i=0; i<this.creepNames.length; i++){
            const creep=Game.creeps[this.creepNames[i]];
            if(!creep){
                this.creepNames[i]=undefined;
                continue;
            }
            if(creep.spawning){
                continue;
            }
            try{
                this.creepRun(creep, ...args);
            }catch(e){
                console.log('Error(from '+creep.name+'):'+e.message+'\n'+e.stack);
            }
        }
        return OK;
    }

    /**
     * 
     * @param {AnyCreep} creep 
     */
    creepRun(creep, ...args){
        let ret;

        if(creep.memory.working){
            this.__currentAction = this.creepWork;
            this.__alternativeAction = this.creepGet;
        }else{
            this.__currentAction = this.creepGet;
            this.__alternativeAction = this.creepWork;
        }

        ret = this.__currentAction(creep, ...args);
        if(ret !== ERR_SWITCH_STATE){
            return ret;
        }

        ret = this.__alternativeAction(creep, ...args);
        if(ret === ERR_SWITCH_STATE){
            return ERR_INVALID_STATE;
        }
        
        creep.memory.working = !creep.memory.working;
        jobGoto.setTargetId(creep, undefined);
        return ret;
    }

    /**
     * 
     * @param {AnyCreep} creep 
     * @returns {GroupActionReturnCode}
     */
    creepWork(creep, ...args){
        return ERR_INVALID_STATE;
    }

    /**
     * 
     * @param {AnyCreep} creep 
     * @returns {GroupActionReturnCode}
     */
    creepGet(creep, ...args){
        return ERR_INVALID_STATE
    }
}